<template>
  
  <div class="at-wrap">
   
    <div class="at-overlay">
      <div class="at-overlay-content"> Music sheet is loading </div>
    </div>
    <div class="at-content">
      <div class="at-sidebar">
        <div class="at-sidebar-content">
          <div ref="trackList" class="at-track-list"> </div>
        </div>
      </div>
      <div class="at-viewport">
        <div ref="atMain" class="at-main"></div>
      </div>
    </div>
    <div class="at-controls">
      <div class="at-controls-left">
        <a class="btn at-player-stop disabled">
          <i class="iconfont icon-backward"></i>
        </a>
        <a class="btn at-player-play-pause disabled">
          <i class="iconfont icon-play"></i>
        </a>
        <span class="at-player-progress">0%</span>
        <div class="at-song-info">
          <span class="at-song-title"></span> -
          <span class="at-song-artist"></span>
        </div>
        <div class="at-song-position">00:00 / 00:00</div>
      </div>
      <div class="at-controls-right">
        <a class="btn toggle at-count-in">
          <i class="iconfont icon-hourglasshalf"></i>
        </a>
        <a class="btn at-metronome">
          <i class="iconfont icon-edit"></i>
        </a>
        <a class="btn at-loop">
          <i class="iconfont icon-retweet"></i>
        </a>
        <a class="btn at-print">
          <i class="iconfont icon-print"></i>
        </a>
        <div class="at-zoom">
          <i class="iconfont icon-search"></i>
          <select>
            <option value="25">25%</option>
            <option value="50">50%</option>
            <option value="75">75%</option>
            <option value="90">90%</option>
            <option value="100" selected>100%</option>
            <option value="110">110%</option>
            <option value="125">125%</option>
            <option value="150">150%</option>
            <option value="200">200%</option>
          </select>
        </div>
        <div class="at-layout">
          <select>
            <option value="horizontal">Horizontal</option>
            <option value="page" selected>Page</option>
          </select>
        </div>
      </div>
    </div>
  </div>

  <div id="at-track-template" class="at-track">
    <div>
      <div class="at-track-icon">
        <i class="iconfont icon-guitar"></i>
      </div>
      <div class="at-track-details">
        <div class="at-track-name"></div>
      </div>
    </div>
  </div>

  <audio ref="audio" :src="audioUrl" preload="auto"></audio> <!-- 新增音频元素 -->
</template>

<script lang="ts" setup>
  import { getCurrentInstance, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import { ref } from 'vue'
  // 获取全局挂载的对象
  const { globalProperties } = getCurrentInstance()?.appContext.config; // 获取全局挂载
  const Query = globalProperties.$Query;
  // @ts-ignore
  const { alphaTab } = window;
  const route = useRoute();
  const querySheetFiles = async (id: string) => {
    const query = new Query('_File');
    const result = await query.get(id);
    console.log('----result', result);
    return result.attributes.url;
  };
  // 新增音频播放相关的引用
  const audio = ref<HTMLAudioElement | null>(null);
  const audioUrl = ref<string>(''); // 存储MP3文件的URL
  const isPlaying = ref<boolean>(false); // 新增状态变量

  onMounted(async () => {
    const queryParams = route.params;
    const { id } = queryParams;
    const wrapper = document.querySelector('.at-wrap');
    const main = wrapper.querySelector('.at-main');
    const overlay = wrapper.querySelector('.at-overlay');
    const trackList = wrapper.querySelector('.at-track-list');
    const countIn = wrapper.querySelector('.at-controls .at-count-in');
    const metronome = wrapper.querySelector('.at-controls .at-metronome');
    const loop = wrapper.querySelector('.at-controls .at-loop');
    const printBtn = wrapper.querySelector('.at-controls .at-print');
    const zoom = wrapper.querySelector('.at-controls .at-zoom select');
    console.log('---zoom', zoom);
    const layout = wrapper.querySelector('.at-controls .at-layout select');
    const playerIndicator = wrapper.querySelector(
      '.at-controls .at-player-progress'
    );
    const playPause = wrapper.querySelector(
      '.at-controls .at-player-play-pause'
    );
    const stop = wrapper.querySelector('.at-controls .at-player-stop');
    const songPosition = wrapper.querySelector('.at-song-position');
    const url = await querySheetFiles(id);
    const soludFontUrl = `${window.location.origin}/sonivox.sf2`;
    const settings = {
      file: url,
      player: {
        enablePlayer: true,
        soundFont: soludFontUrl,
        scrollElement: wrapper.querySelector('.at-viewport'),
      },
    };

    const api = new alphaTab.AlphaTabApi(main, settings);

    api.renderStarted.on(() => {
      overlay.style.display = 'flex';
    });

    api.renderFinished.on(() => {
      overlay.style.display = 'none';
    });

    function createTrackItem(track) {
      const dom = document.querySelector('#at-track-template');
      const trackItem = dom?.cloneNode(true).firstElementChild;
      trackItem.querySelector('.at-track-name').innerText = track.name;
      trackItem.track = track;
      trackItem.onclick = (e) => {
        e.stopPropagation();
        api.renderTracks([track]);
      };
      return trackItem;
    }

    api.scoreLoaded.on((score) => {
      wrapper.querySelector('.at-song-title').innerText = score.title;
      wrapper.querySelector('.at-song-artist').innerText = score.artist;
      trackList.innerHTML = '';
      score.tracks.forEach((track) => {
        trackList.appendChild(createTrackItem(track));
      });

      audioUrl.value = '/小星星.mp3'; // 假设score中有audioUrl属性
      if (audio.value) {
        audio.value.src = audioUrl.value; // 设置音频源
      }
    });

    api.renderStarted.on(() => {
      const tracks = new Map();
      api.tracks.forEach((t) => {
        tracks.set(t.index, t);
      });
      trackList.querySelectorAll('.at-track').forEach((trackItem) => {
        trackItem.classList.toggle('active', tracks.has(trackItem.track.index));
      });
    });

    countIn.onclick = () => {
      countIn.classList.toggle('active');
      api.countInVolume = countIn.classList.contains('active') ? 1 : 0;
    };

    metronome.onclick = () => {
      metronome.classList.toggle('active');
      api.metronomeVolume = metronome.classList.contains('active') ? 1 : 0;
    };

    loop.onclick = () => {
      loop.classList.toggle('active');
      api.isLooping = loop.classList.contains('active');
    };

    printBtn.onclick = () => {
      api.print();
    };

    zoom.onchange = () => {
      api.settings.display.scale = parseInt(zoom.value, 10) / 100;
      api.updateSettings();
      api.render();
    };

    layout.onchange = () => {
      api.settings.display.layoutMode =
        layout.value === 'horizontal'
          ? alphaTab.LayoutMode.Horizontal
          : alphaTab.LayoutMode.Page;
      api.updateSettings();
      api.render();
    };

    api.soundFontLoad.on((e) => {
      playerIndicator.innerText = `${Math.floor((e.loaded / e.total) * 100)}%`;
    });

    api.playerReady.on(() => {
      console.log('----playerReady 开始播放')
      playerIndicator.style.display = 'none';
      playPause.classList.remove('disabled');
      stop.classList.remove('disabled');

      // if (audio.value) {
      //   console.log('----开始播放', audio.value)
      //   audio.value.play(); // 开始播放音频
      //   isPlaying.value = true; // 更新播放状态
      // }
    });

    playPause.onclick = (e) => {
      if (!e.target.classList.contains('disabled')) {
        if (isPlaying.value) {
          audio.value?.pause(); // 暂停音频
          isPlaying.value = false; // 更新播放状态
          console.log('----我开始暂停了')
        } else {
          audio.value?.play(); // 播放音频
          isPlaying.value = true; // 更新播放状态
          console.log('----当前的播放时间为: audio.value.currentTime ', audio.value?.currentTime )
          console.log('----我开始播放了')
        }
        api.playPause(); // 切换alphaTab的播放状态
      }
    };

    stop.onclick = (e) => {
      if (!e.target.classList.contains('disabled')) {
        api.stop();
      }
    };

    api.playerStateChanged.on((e) => {
      const icon = playPause.querySelector('i.iconfont');
      icon.classList.toggle(
        'icon-play',
        e.state !== alphaTab.synth.PlayerState.Playing
      );
      icon.classList.toggle(
        'icon-pausecircle',
        e.state === alphaTab.synth.PlayerState.Playing
      );

      // 根据alphaTab的状态更新isPlaying
      isPlaying.value = e.state === alphaTab.synth.PlayerState.Playing;
    });

    function formatDuration(milliseconds) {
      const seconds = Math.floor(milliseconds / 1000);
      const minutes = Math.floor(seconds / 60);
      return `${String(minutes).padStart(2, '0')}:${String(
        seconds % 60
      ).padStart(2, '0')}`;
    }

    let previousTime = -1;
    api.playerPositionChanged.on((e) => {
      const currentSeconds = Math.floor(e.currentTime / 1000);
      if (currentSeconds !== previousTime) {
        previousTime = currentSeconds;
        songPosition.innerText = `${formatDuration(
          e.currentTime
        )} / ${formatDuration(e.endTime)}`;

        // 根据alphaTab的时间控制音频播放
        if (audio.value) {
          audio.value.currentTime = e.currentTime / 1000; // 设置音频播放时间
        }
      }
    });
  });

  // 获取当前alphaTab的播放状态
  function getAlphaTabPlayState() {
    return isPlaying.value; // 返回当前播放状态
  }
</script>

<style>
  .at-wrap {
    width: 100%;
    height: 80vh;
    margin: 0 auto;
    border: 1px solid rgba(0, 0, 0, 0.12);
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    margin-top: 100px;
  }

  .at-content {
    position: relative;
    overflow: hidden;
    flex: 1 1 auto;
  }

  /** Sidebar **/
  .at-sidebar {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    max-width: 70px;
    width: auto;
    display: flex;
    align-content: stretch;
    z-index: 1001;
    overflow: hidden;
    border-right: 1px solid rgba(0, 0, 0, 0.12);
    background: #f7f7f7;
  }

  .at-sidebar:hover {
    max-width: 400px;
    transition: max-width 0.2s;
    overflow-y: auto;
  }

  .at-viewport {
    overflow-y: auto;
    position: absolute;
    top: 0;
    left: 70px;
    right: 0;
    bottom: 0;
    padding-right: 20px;
  }

  .at-footer {
    flex: 0 0 auto;
    background: #436d9d;
    color: #fff;
  }

  /** Overlay **/

  .at-overlay {
    /** Fill Parent */
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1002;

    /* Blurry dark shade */
    backdrop-filter: blur(3px);
    background: rgba(0, 0, 0, 0.5);

    /** center content */
    display: flex;
    justify-content: center;
    align-items: flex-start;
  }

  .at-overlay-content {
    /* white box with drop-shadow */
    margin-top: 20px;
    background: #fff;
    box-shadow: 0px 5px 10px 0px rgba(0, 0, 0, 0.3);
    padding: 10px;
  }

  /** Track selector **/
  .at-track {
    display: flex;
    position: relative;
    padding: 5px;
    transition: background 0.2s;
    cursor: pointer;
  }

  .at-track:hover {
    background: rgba(0, 0, 0, 0.1);
  }

  .at-track > .at-track-icon,
  .at-track > .at-track-details {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .at-track > .at-track-icon {
    flex-shrink: 0;
    font-size: 32px;
    opacity: 0.5;
    transition: opacity 0.2s;
    width: 64px;
    height: 64px;
    margin-right: 5px;
    align-items: center;
  }

  .at-track-name {
    font-weight: bold;
    margin-bottom: 5px;
  }

  .at-track:hover > .at-track-icon {
    opacity: 0.8;
  }

  .at-track.active {
    background: rgba(0, 0, 0, 0.03);
  }

  .at-track.active > .at-track-icon {
    color: #4972a1;
    opacity: 1;
  }

  .at-track > .at-track-name {
    font-weight: 500;
  }

  /** Footer **/
  .at-controls {
    flex: 0 0 auto;
    display: flex;
    justify-content: space-between;
    background: #436d9d;
    color: #fff;
  }

  .at-controls > div {
    display: flex;
    justify-content: flex-start;
    align-content: center;
    align-items: center;
  }

  .at-controls > div > * {
    display: flex;
    text-align: center;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 4px;
    margin: 0 3px;
  }

  .at-controls .btn {
    color: #fff;
    border-radius: 0;
    height: 40px;
    width: 40px;
    height: 40px;
    font-size: 16px;
  }

  .at-controls .btn.disabled {
    cursor: progress;
    opacity: 0.5;
  }

  .at-controls a.active {
    background: #5588c7;
    text-decoration: none;
  }

  .at-controls .btn i {
    vertical-align: top;
  }

  .at-controls select {
    -moz-appearance: none;
    -webkit-appearance: none;
    appearance: none;
    border: none;
    width: 100%;
    height: 40px;
    background: #436d9d;
    padding: 4px 10px;
    color: #fff;
    font-size: 16px;
    text-align-last: center;
    text-align: center;
    -ms-text-align-last: center;
    -moz-text-align-last: center;
    cursor: pointer;
  }

  .at-song-title {
    font-weight: bold;
  }

  .at-cursor-bar {
    /* Defines the color of the bar background when a bar is played */
    background: rgba(255, 242, 0, 0.25);
  }

  .at-selection div {
    /* Defines the color of the selection background */
    background: rgba(64, 64, 255, 0.1);
  }

  .at-cursor-beat {
    /* Defines the beat cursor */
    background: rgba(64, 64, 255, 0.75);
    width: 3px;
  }

  .at-highlight * {
    /* Defines the color of the music symbols when they are being played (svg) */
    fill: #0078ff;
    stroke: #0078ff;
  }
</style>
